package com.coursemanage.course;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.common.util.ExcelExport;
import com.common.util.ExcelRead;
import com.common.util.VeDateUtil;
import com.coursemanage.common.model.Course;
import com.coursemanage.common.model.Message;
import com.coursemanage.common.model.Schools;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

public class CourseController extends Controller {

	public void index() {
//		List<Course> courses=new ArrayList<Course>();
//		for (int i = 0; i < 1900; i++) {
//			 Course course =new Course();
//			 course.setName("测试");
//			 course.setSchoolId(7);	
//			  courses.add(course);
//		}
//		Db.batchSave(courses, 50);
		render("index.jsp");
	}
	public void page() {
		Page<Course> courses=Course.dao.paginate(getParaToInt("pageNumber"), 
				getParaToInt("pageSize"),getPara("keyword"),getPara("sortName"),getPara("order"));
		Ret ret=new Ret();
		ret.put("rows", courses.getList());
		ret.put("total", courses.getTotalRow());
		setAttrs(ret);
	   renderJson();
	}
	public void update(){
		Course course=getModel(Course.class,"course");
		course.update();
	    Message msg=new Message();
	    msg.setMsg(true,200,"更新成功！");
		renderJson(msg);
	}
	public void save(){
		Course course=getModel(Course.class,"course");
		Message msg=new Message();
		course.save();
	   msg.setMsg(true,200,"添加成功！");
	   renderJson(msg);
	}
	public void imports(){
		setAttr("schools",Schools.dao.find("select id,name from schools"));
		render("imports.jsp");
	}
	public void exports(){
		setAttr("schools",Schools.dao.find("select id,name from schools"));
		render("exports.jsp");
	}
	public void CreatOrEdit(){
		Integer id=getParaToInt(0);
		Course course=id!=null&&id>0?Course.dao.findById(id):new Course();
		Ret ret=new Ret();
		boolean isEdit=false;
		if (course.getId()!=null) {
			isEdit=true;	
		}
		ret.put("schools",Schools.dao.find("select id,name from schools"));
		ret.put("isEdit",isEdit);
		ret.put("course",course);
		setAttrs(ret);
		render("CreatOrEdit.jsp");
	}
	public void del(){
		String[] ids=getParaValues("ids");
		
		if(ids!=null&&ids.length>-1&&ids.length==1){
			//执行删除操作
		  Db.deleteById("course", "id", ids[0]);		
		}else if(ids.length>1){
			
			//批量删除操作
			String sql="delete from course where id in(?)";
			Object id_no_arr[][]=new Object[ids.length][1];
			for(int i=0;i<ids.length;i++){
				for(int j=0;j<1;j++){
					id_no_arr[i][j]=ids[i];
				}
			}
			int[] size= Db.batch(sql,id_no_arr, id_no_arr.length);
		}
		Message msg = new Message();
		msg.setMsg(true, 200, "删除成功！");
		renderJson(msg);
	}
	public void exportData() throws IOException {
		 int schoolId=getParaToInt("schoolId");
		 String schoolName=getPara("schoolName");
		 List<Course> list =Course.dao.find("select * from course where school_id="+schoolId);    
		   File file = new File(schoolName+"_课程表"+".xls");  
	        HSSFWorkbook wb =new ExcelExport().export(list,schoolName);    
	        FileOutputStream fileOutputStreane = new FileOutputStream(file);  
	        wb.write(fileOutputStreane);  
            fileOutputStreane.flush();  
            fileOutputStreane.close();  
            renderFile(file);;
	}
	public void importData() throws Exception{
		UploadFile upfile=getFile();
	   int schoolId=getParaToInt("schoolId");
    	String uploadpath=upfile.getUploadPath().replace("/","\\")+"\\";
    	String fileName=uploadpath+upfile.getFileName();
    	   List<List<String>> result = new ExcelRead().readXlsx(fileName);
    	   List<Course> courselist=new ArrayList<Course>();
           List<String> courses=new ArrayList<String>();
           List<String[]> strArray = new ArrayList();  
           for (int i = 0; i < result.size(); i++) {
               List<String> model = result.get(i);
               System.err.println(model.size());
             for (int j = 0; j < model.size(); j++) {
           		  if(model.get(j)!="无"){
           			  strArray.add(model.get(j).replace(",", "，").split("，"));
				}
			}
            for (String[] string : strArray) {
           	 for (String str : string) {
	            	   if(!courses.contains(str)){
	            		   courses.add(str);
	            	   }
				   }
			}   
           }
           for (String name : courses) {
        	   Course course =new Course();
        	   if (course.find("select * from course where course.name='"+name+"' and school_id="+schoolId).size()==0) {
        		   {	
        		   course.setName(name);
        		   course.setSchoolId(schoolId);
        		   courselist.add(course);
        		   }
		}
       }
         int size=courses.size();
         Db.batchSave(courselist, 50);
        System.err.println(size);
    	Message msg=new Message();
 	    msg.setMsg(true,200,"导入成功！");
 	   msg.setPara(courses.size());
 		renderJson(msg);
	
   }
}
